package com.mzj.saas.mservice.smartlock.service.haixiaoke;

import cn.hutool.core.util.ObjectUtil;
import com.mzj.saas.mservice.lock.Repository.*;
import com.mzj.saas.mservice.lock.entity.SmartLock;
import com.mzj.saas.mservice.lock.entity.SmartLockAuth;
import com.mzj.saas.mservice.lock.service.LockAppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Dell
 * @Date 2023/10/8
 **/
@Slf4j
@Service
public class SmartLockHxkEventHandleService {

    @Autowired
    private SmartLockRepository smartLockRepository;
    @Autowired
    private SmartLockAuthRepository smartLockAuthRepository;
    @Autowired
    private SmartLockPwdRepository smartLockPwdRepository;
    @Autowired
    private SmartLockFaceRepository smartLockFaceRepository;
    @Autowired
    private SmartLockCardRepository smartLockCardRepository;
    @Autowired
    private LockAppService lockAppService;

    /**
     * 删除用户的授权信息数据
     * @param sn
     * @return
     */

    @Transactional
    public Map<String, Object> deleteAuth(String sn) {
        Map<String,Object> result = new HashMap<>();
        result.put("code",1);
        result.put("msg","操作失败");
        SmartLock smartLock = smartLockRepository.findBySn(sn);
        if (ObjectUtil.isNotEmpty(smartLock)) {
            Long lockId = smartLock.getId();
            if (lockId != null) {
                smartLockPwdRepository.deleteByLockId(lockId);
                smartLockCardRepository.deleteByLockId(lockId);
                smartLockFaceRepository.deleteByLockId(lockId);
                List<SmartLockAuth> authList = smartLockAuthRepository.findByLockId(lockId);
                authList.forEach(x->{
                    x.setPwdStatus(0);
                    x.setCardStatus(0);
                    x.setFaceStatus(0);
                });
                //修改房屋授权人的授权信息状态
                smartLockAuthRepository.saveAll(authList);
                //更新已授权人数
                lockAppService.updateOauthNumber(5L,lockId);
                result.put("code",0);
                result.put("msg","操作成功");
                return result;
            }
            log.error("该sn：{}，查询不到该设备",sn);
        }
        return result;
    }
}
